package com.wzb.mybatisplus.bitaction.electrumaction;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;

public class ByteStreamElectrumClient {

    public static void main(String[] args) {
        try {

            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket socket = (SSLSocket) factory.createSocket("electrum.bitaroo.net", 50002);
            socket.setSoTimeout(30000);

            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            // 发送请求
            String request = "{\"id\":0,\"method\":\"server.version\",\"params\":[\"test\",\"1.4\"],\"jsonrpc\":\"2.0\"}\n";
            System.out.println("发送: " + request);

            outputStream.write(request.getBytes());
            outputStream.flush();

            // 使用字节流读取响应
            System.out.println("等待响应...");
            byte[] buffer = new byte[4096];
            int totalBytesRead = 0;
            long startTime = System.currentTimeMillis();

            while (true) {
                if (System.currentTimeMillis() - startTime > 25000) {
                    System.out.println("超时，停止等待");
                    break;
                }

                if (inputStream.available() > 0) {
                    int bytesRead = inputStream.read(buffer, totalBytesRead, buffer.length - totalBytesRead);
                    if (bytesRead == -1) break;

                    totalBytesRead += bytesRead;

                    String partialResponse = new String(buffer, 0, totalBytesRead);
                    System.out.println("已读取 " + totalBytesRead + " 字节: " + partialResponse);

                    // 检查是否收到完整JSON
                    if (partialResponse.trim().endsWith("}")) {
                        System.out.println("收到完整响应");
                        break;
                    }
                } else {
                    Thread.sleep(100);
                }
            }

            String finalResponse = new String(buffer, 0, totalBytesRead);
            System.out.println("最终响应: " + finalResponse);

            inputStream.close();
            outputStream.close();
            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}